<template>
  <PageWrapper>
    <n-grid cols="1 s:1 m:1 l:4 xl:4 2xl:4" responsive="screen" :x-gap="12">
      <n-gi span="1">
        <n-card :segmented="{ content: 'soft' }" :bordered="false" size="small">
          <template #header>
            <n-space>
              <n-button type="info" icon-placement="left" @click="openCreateDrawer">
                添加菜单
                <template #icon>
                  <div class="flex items-center">
                    <n-icon size="14">
                      <FileAddOutlined />
                    </n-icon>
                  </div>
                </template>
              </n-button>

              <n-button type="info" ghost icon-placement="left" @click="packHandle">
                全部{{ expandedKeys.length ? '收起' : '展开' }}
                <template #icon>
                  <div class="flex items-center">
                    <n-icon size="14">
                      <AlignLeftOutlined />
                    </n-icon>
                  </div>
                </template>
              </n-button>
            </n-space>
          </template>
          <div class="w-full menu">
            <n-input type="text" v-model:value="pattern" placeholder="输入菜单名称搜索">
              <template #suffix>
                <n-icon size="18" class="cursor-pointer">
                  <SearchOutlined />
                </n-icon>
              </template>
            </n-input>
            <div class="py-3 menu-list">
              <template v-if="loading">
                <div class="flex items-center justify-center py-4">
                  <n-spin size="medium" />
                </div>
              </template>
              <template v-else>
                <n-tree
                  block-line
                  cascade
                  :virtual-scroll="true"
                  :pattern="pattern"
                  :data="treeData"
                  key-field="id"
                  label-field="name"
                  :expandedKeys="expandedKeys"
                  style="max-height: 650px; overflow: hidden"
                  @update:selected-keys="selectedTree"
                  @update:expanded-keys="onExpandedKeys"
                />
              </template>
            </div>
          </div>
        </n-card>
      </n-gi>
      <n-gi span="3">
        <n-card :segmented="{ content: 'soft' }" :bordered="false" size="small">
          <template #header>
            <n-space>
              <span>编辑分类 {{ treeItemTitle ? `：${treeItemTitle}` : '' }}</span>
              <n-divider vertical />
              <n-text depth="3" class="text-sm"> 从左侧列表选择一项后，进行编辑 </n-text>
            </n-space>
          </template>
          <template #header-extra>
            <n-popconfirm @positive-click="handleDeleteCategory" v-if="isEditCategory">
              <template #trigger>
                <n-button quaternary type="info">删除分类</n-button>
              </template>
              确定要删除 {{ treeItemTitle }} 分类吗？
            </n-popconfirm>
          </template>
          <!-- 表单 -->
          <n-spin :show="loadingR">
            <CategoryForm
              ref="categoryFormRef"
              :permissionList="treeData"
              @change="categoryChange"
              class="w-2/4 ml-10"
              isShowSubmit
            />
          </n-spin>
        </n-card>
      </n-gi>
    </n-grid>
    <CreateDrawer
      ref="createDrawerRef"
      :title="drawerTitle"
      :permissionList="treeData"
      @change="categoryChange"
    />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { ref, unref, onMounted } from 'vue';
  import { useMessage } from 'naive-ui';
  import { AlignLeftOutlined, SearchOutlined, FileAddOutlined } from '@vicons/antd';
  import {
    merchantCategoryTree,
    merchantCategoryInfo,
    deleteMerchantCategory,
  } from '@/api/merchant/merchant';
  import { getTreeItem } from '@/utils';
  import CreateDrawer from './CreateDrawer.vue';
  import CategoryForm from './CategoryForm.vue';

  const createDrawerRef = ref();
  const message = useMessage();

  let treeItemKey = ref([]);

  let expandedKeys = ref([]);

  const treeData = ref([]);

  const loading = ref(true);
  const loadingR = ref(false);

  const isEditCategory = ref(false);
  const treeItemTitle = ref('');
  const pattern = ref('');
  const drawerTitle = ref('');
  const categoryFormRef = ref();

  const formParams = ref({
    id: null,
    parent_id: 0,
    name: '',
    icon: [],
    order: 1,
    status: false,
  });

  function handleDeleteCategory() {
    const categoryId = formParams.value.id;
    deleteMerchantCategory(categoryId).then(() => {
      message.success('删除成功!');
      isEditCategory.value = false;
      treeItemTitle.value = '';
      categoryFormRef.value.handleReset();
      getMerchantCategory();
    });
    // deleteMenu({ id: formParams.value.id }).then(() => {
    //   message.success('删除成功');
    //   isEditMenu.value = false;
    //   treeItemTitle.value = '';
    //   categoryFormRef.value.handleReset();
    //   getInformationCategory();
    // });
  }

  function openCreateDrawer() {
    drawerTitle.value = '添加菜单';
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  }

  async function selectedTree(keys) {
    if (keys.length) {
      const treeItem = getTreeItem(unref(treeData), keys[0], 'id');
      treeItemKey.value = keys;
      treeItemTitle.value = treeItem.name;
      loadingR.value = true;
      const info = await merchantCategoryInfo(keys[0]);
      const newCategoryInfo = {
        id: info.id,
        parent_id: info.parent_id,
        name: info.name,
        icon: info.icon ? [info.icon] : [],
        order: info.order,
        status: true,
      };
      formParams.value = newCategoryInfo;
      categoryFormRef.value.setData(newCategoryInfo);
      isEditCategory.value = true;
      loadingR.value = false;
    } else {
      isEditCategory.value = false;
      treeItemKey.value = [];
      treeItemTitle.value = '';
    }
  }

  function packHandle() {
    if (expandedKeys.value.length) {
      expandedKeys.value = [];
    } else {
      expandedKeys.value = unref(treeData).map((item: any) => item.id) as [];
    }
  }

  async function getMerchantCategory() {
    loading.value = true;
    const cateTree = await merchantCategoryTree();
    treeData.value = cateTree;
    loading.value = false;
  }

  async function categoryChange() {
    getMerchantCategory();
    treeItemTitle.value = '';
    isEditCategory.value = false;
  }

  onMounted(async () => {
    getMerchantCategory();
  });

  function onExpandedKeys(keys) {
    expandedKeys.value = keys;
  }
</script>

<style lang="less" scoped></style>
